package alg;
import java.text.DecimalFormat;
import java.util.Random;

public class LMS {

	double[] w;

	public LMS(int n_entradas) {

		w = new double[n_entradas];

	}

	public void inicializar() {

		Random Gerador = new Random();

		for (int i = 0; i < w.length; i++) {

			w[i] = Gerador.nextFloat();
		}

	}

	public int treinar(double[][] matriz, double[] d, int nSamples, double e) {

		double n = 0.1;
		int epoca = 0;
		double u = 0;
		double y;
		double atual;
		


		do {


			for (int i = 0; i < nSamples; i++) {

				u = 0;

				for (int j = 0; j < w.length; j++) {

					u = u + (w[j] * matriz[i][j]);

				}

				y = 1 / (1 + Math.exp(-1 * u));
				
				for (int j = 0; j < w.length; j++) {

					w[j] = w[j] + (n * (d[i] - y) * matriz[i][j]);

				}

			}

			epoca = epoca + 1;
			atual = eqm(w, d, matriz,nSamples);
			
		} while (atual >= e);
		
		return epoca;

	}

	double eqm(double w[], double d[], double[][] matriz, int nSamples) {

		double e = 0;
		double u;
		double y;

		for (int i = 0; i < nSamples; i++) {

			u = 0;

			for (int j = 0; j < w.length; j++) {

				u = u + (w[j] * matriz[i][j]);

			}

			y = 1 / (1 + Math.exp(-1 * u));
			
			e = e + (Math.pow((d[i] - y), 2)/2);

		}
		e = (e / nSamples);

		return e;

	}

	
	public String classificar(double[] value) {
		
		
		double u=0;
		double y;

		for (int j=0; j< value.length; j++){

		u = u + (w[j]*value[j]);

		}

		y = 1 / (1 + Math.exp(-1 * u));
		
		DecimalFormat df = new DecimalFormat("0.##");
		String saida = df.format(y*100);
		
		return saida;
		
	}
	
	
}
